package handler

import (
	"album-api/internal/logic"
	"album-api/internal/svc"
	"album-api/internal/types"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"io"
	common "listenboos-common"
	"listenboos-common/tools"
	"listenboos-common/tools/minioTool"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

type AlbumHandler struct {
	svcCtx *svc.ServiceContext
}

func NewLoginHandler(svcCtx *svc.ServiceContext) *AlbumHandler {
	return &AlbumHandler{
		svcCtx: svcCtx,
	}
}
func (h *AlbumHandler) GetAllCategoryList(w http.ResponseWriter, r *http.Request) {
	logx.Info("调用了GetAllCategoryList接口")
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}

	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	resp, err := l.GetAllCategoryList()
	if err != nil {
		result := newResult.Deal(109, errors.New("获取全部专辑信息错误"))
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	result := newResult.Deal(resp, err)
	//results := []*common.Result{}
	//results = append(results, result)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}
func (h *AlbumHandler) SaveAlbumInfo(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.SaveAlbumInfoReq
	if err := httpx.ParseJsonBody(r, &req); err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	resp, err := l.SaveAlbumInfo(token, req)
	if err != nil {
		result := newResult.Deal(4002, errors.New("保存专辑信息错误"))
		//newResult.Fail(208, "未登录")
		httpx.WriteJsonCtx(r.Context(), w, 4002, result)
		return
	}
	result := newResult.Deal(resp, err)
	//results := []*common.Result{}
	//results = append(results, result)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) FindAttribute(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	cotegory1Id := strings.TrimPrefix(path, "/api/album/category/findAttribute/")
	newResult := common.NewResult()
	if cotegory1Id == "" || cotegory1Id == "undefined" {
		httpx.OkJsonCtx(r.Context(), w, newResult.Deal(nil, errors.New("FindAttribute error")))
		//	return
		cotegory1Id = "2"
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	resp, err := l.FindAttribute(cotegory1Id)
	if err != nil {
		result := newResult.Deal(109, errors.New("获取全部专辑信息错误"))
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	result := newResult.Deal(resp, err)
	//results := []*common.Result{}
	//results = append(results, result)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) FileUpload(w http.ResponseWriter, r *http.Request) {
	//token := r.Header.Get("token")
	newResult := common.NewResult()
	//if token == "" {
	//	result := newResult.NoLogin(208, "未登录")
	//	//newResult.Fail(208, "未登录")
	//	httpx.OkJsonCtx(r.Context(), w, result)
	//	return
	//}
	file, handler, err := r.FormFile("file")
	if err != nil {
		result := newResult.Deal(109, errors.New("上传专辑信息失败"))
		httpx.WriteJsonCtx(r.Context(), w, 4001, result)
		return
	}
	filePath := "D:/VScode/WorkSpace/listenbooks-go-gozero/images"
	// 创建保存文件的目录（如果不存在则创建）
	err = os.MkdirAll(filePath, os.ModePerm)
	if err != nil {
		httpx.Error(w, err)
		return
	}
	md5 := tools.Md5(handler.Filename)
	ext := filepath.Ext(handler.Filename)
	fileName := md5 + ext
	// 生成文件保存路径
	dst, err := os.Create(filepath.Join(filePath, fileName))
	if err != nil {
		http.Error(w, "Unable to create the file on server", http.StatusInternalServerError)
		return
	}
	//out, err := os.Create(dst)
	_, err = io.Copy(dst, file)
	if err != nil {
		httpx.Error(w, err)
		return
	}
	defer file.Close()
	defer dst.Close()
	//假设只上传一个文件
	key := "sss/" + md5 + ext
	minioClient, err := minioTool.NewMinio()
	bucketName := "sss"
	err = minioClient.UploadFile(bucketName,
		fileName,
		filePath+"/"+fileName,
	)
	if err != nil {
		httpx.WriteJsonCtx(r.Context(), w, -999, errors.New("保存专辑文件失败"))
		return
	}
	go func() {
		err = os.Remove(filePath + "/" + fileName)
		if err != nil {
			// 如果删除失败，打印错误信息
			fmt.Printf("Error removing file: %v\n", err)
			return
		}
	}()
	url := "http://192.168.2.9:9009/" + key
	resp := newResult.Deal(url, nil)
	httpx.OkJsonCtx(r.Context(), w, resp)
	return
}

func (h *AlbumHandler) FindUserAlbumPage(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.FindUserAlbumReq
	if err := httpx.ParsePath(r, &req); err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	resp, err := l.FindUserAlbumPage(token, req)
	if err != nil {
		result := newResult.Deal(4003, errors.New("未查到发布专辑的信息"))
		//newResult.Fail(208, "未登录")
		httpx.WriteJsonCtx(r.Context(), w, 4002, result)
		return
	}
	result := newResult.Deal(resp, err)
	//results := []*common.Result{}
	//results = append(results, result)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) GetAlbumInfoById(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.DetailReq
	if err := httpx.ParsePath(r, &req); err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	resp, err := l.GetAlbumInfoById(token, req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑的信息"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(resp, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) RemoveAlbumInfo(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.RemoteAlbumReq
	if err := httpx.ParsePath(r, &req); err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	err := l.RemoveAlbumInfo(token, req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑的信息"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(nil, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) FindUserAllAlbumList(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.FindUserAllAlbumList(token)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) GetCategory3ListByCategory1Id(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	var req types.Category1Req
	err := httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.GetCategory3ListByCategory1Id(req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) Channel(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	var req types.Category1Req
	err := httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.GetChannel(req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) GetBaseCategoryList3(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	var req types.Category1Req
	err := httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.GetBaseCategoryList3(req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) AlbumInfo(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	var req types.AlbumInfoReq
	err := httpx.ParseJsonBody(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.SearchAlbumInfo(req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) KeyWord(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	var req types.KeyWordReq
	err := httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.KeyWord(req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) FindAlbumInfo(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	var req types.FindAlbumInfoReq
	err := httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.FindAlbumInfo(req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) FindAlbumTrackPage(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	userId, _ := tools.ParseToken(token, h.svcCtx.Config.JWT.AccessSecret)
	var req types.FindTrackReq
	err := httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.FindAlbumTrackPage(req, userId)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h *AlbumHandler) FindRankingList(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	var req types.FindRankingListReq
	err := httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.FindRankingList(req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

// UpdateListenProcess 更新播放进度
func (h *AlbumHandler) UpdateListenProcess(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	//if token == "" {
	//	httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "未登录"))
	//	return
	//}
	userId, err := tools.ParseToken(token, h.svcCtx.Config.JWT.AccessSecret)
	if err != nil {
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "未登录"))
		return
	}
	var req types.UpdateListenReq
	err = httpx.ParseJsonBody(r, &req)
	if err != nil {
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(1209, "参数解析出错"))
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	err = l.UpdateListenProcess(req, userId)
	if err != nil {
		logx.Errorf("error:", err)
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(1209, "保存进度失败"))
		return
	}
	result := newResult.Deal(nil, err)
	httpx.OkJsonCtx(r.Context(), w, result)
}

func (h *AlbumHandler) GetLatelyTack(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	//if token == "" {
	//	httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "未登录"))
	//	return
	//}
	userId, err := tools.ParseToken(token, h.svcCtx.Config.JWT.AccessSecret)
	if err != nil {
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "未登录"))
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.GetLatelyTack(userId)
	if err != nil {
		logx.Errorf("error:", err)
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(1209, "获取进度失败"))
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
}

func (h *AlbumHandler) GetTrackStatVo(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	var req types.GetTrackStatVoReq
	err := httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.GetTrackStatVo(req)
	if err != nil {
		logx.Errorf("error:", err)
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(1209, "获取进度失败"))
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)

}

func (h *AlbumHandler) findUserTrackPaidList(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	userId, err := tools.ParseToken(token, h.svcCtx.Config.JWT.AccessSecret)
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.GetTrackStatVoReq
	err = httpx.ParsePath(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.FindUserTrackPaidList(req, userId)
	if err != nil {
		logx.Errorf("error:", err)
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(1209, "获取进度失败"))
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
}

func (h *AlbumHandler) OrderInfo(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	userId, err := tools.ParseToken(token, h.svcCtx.Config.JWT.AccessSecret)
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.OrderInfoReq
	err = httpx.ParseJsonBody(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.OrderInfo(req, userId)
	if err != nil {
		logx.Errorf("error:", err)
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(1209, "获取进度失败"))
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
}

func (h *AlbumHandler) SubmitOrder(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	userId, err := tools.ParseToken(token, h.svcCtx.Config.JWT.AccessSecret)
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.SubmitOrderReq
	err = httpx.ParseJsonBody(r, &req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未获取到请求参数"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	res, err := l.SubmitOrder(req, userId)
	if err != nil {
		logx.Errorf("error:", err)
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(1209, "获取进度失败"))
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
}
